package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.query.MenuQueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.LogicException;
import cn.wolfcode.crm.util.MenuUtil;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    //页面跳转
    @RequestMapping()
    public String list() {
        return "menu/list";
    }

    //分页
    @RequestMapping("list")
    @ResponseBody
    public PageResult page(MenuQueryObject qo) {
        PageResult page = menuService.queryPage(qo);
        return page;
    }

    //查询所有
    @RequestMapping("selectAll")
    @ResponseBody
    public List<Menu> input() {
        return menuService.listAll();
    }

    //添加
    @RequestMapping("save")
    @ResponseBody
    public JsonResult save(Menu menu) {
        JsonResult jr = new JsonResult();
        try {
            menuService.save(menu);
        } catch (LogicException e) {
            e.printStackTrace();
            jr.setMsg(e.getMessage());
        }
        return jr;
    }

    //修改
    @RequestMapping("update ")
    @ResponseBody
    public JsonResult saveAndUpdate(Menu menu) {
        JsonResult jr = new JsonResult();
        try {
            menuService.update(menu);
        } catch (LogicException e) {
            e.printStackTrace();
            jr.setMsg(e.getMessage());
        }
        return jr;
    }

    //删除
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        JsonResult jr = new JsonResult();
        try {
            menuService.delete(id);
        } catch (LogicException e) {
            e.printStackTrace();
            jr.setMsg(e.getMessage());
        }
        return jr;
    }

    @RequestMapping("nodes")
    @ResponseBody
    public List<Menu> zTree(HttpSession session) {
        Object attribute = session.getAttribute(MenuUtil.JSON_MENUS_ON_SESSION);
        if(attribute == null){
            List<Menu> nodes = menuService.getNodes();
            MenuUtil.filtermenu(nodes);
            session.setAttribute(MenuUtil.JSON_MENUS_ON_SESSION, nodes);
        }
        return (List<Menu>)attribute;
    }
}
